// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  async kaidanlistAction() {
    const searchinfo = JSON.parse(this.post('searchinfo'));

    const where = {
      'o.departmentid': this.shop_userinfo.departmentid
    };

    if (searchinfo.times && (searchinfo.times[0] != null && searchinfo.times[1] != null)) {
      const begintime = Math.floor(new Date(searchinfo.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(searchinfo.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400; // 当天加上一天
      where['o.addtime'] = {'>=': begintime, '<': endtime};
    }

    if (searchinfo.ordertype != 0) where['o.ordertype'] = searchinfo.ordertype;
    where['o.status'] = searchinfo.status == 0 ? ['!=', 0] : searchinfo.status;
    if (searchinfo.search) where['g.name'] = ['like', '%' + searchinfo.search + '%'];

    const list = await this.model('or_shop_order')
      .alias('o')
      .field('o.*, g.name')
      .join('`think_or_guest` g on g.id=o.guestid')
      .where(where)
      .page(searchinfo.currentPage, searchinfo.pageSize)
      .order('o.addtime desc')
      .countSelect();

    return this.json(list);
  }

  // 分配提成
  async fenpeitichengAction() {
    const data = JSON.parse(this.post('userinfo'));
    const orderid = this.post('orderid');
    const ordertype = this.post('ordertype');
    const addtime = Math.round(new Date().getTime() / 1000);
    const orderinfo = await this.model('or_shop_order').where({id: orderid}).find();

    // 默认为流水单
    const isCanEditOrder = await this.isCanEditOrder(orderid, ordertype);
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    if (orderinfo.status == 2) {
      return this.fail('该订单已经分配业绩！');
    }

    // 确定发放月份
    const unix = new Date(orderinfo.addtime * 1000);
    const nYear = unix.getFullYear();
    let nMonth = unix.getMonth() + 1;
    nMonth = nMonth < 10 ? '0' + nMonth : nMonth;
    const jiesuandate = nYear + '' + nMonth;

    let basepay = [], fenpeitichengdata = [];
    for (let i = 0, len = data.length; i < len; i++) {
      // 查询员工当月工资有没有发放
      const isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find();
      if (!think.isEmpty(isfafang)) {
        return this.fail('该订单时间段内有员工的工资已经发放！');
      }

      // 根据data去分配basetype
      if (data[i].xianjinticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 1,
          money: data[i].xianjinticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 1,
          yeji: data[i].xianjinyeji,
          money: data[i].xianjinticheng,
          tichengbi: 0
        });
      }
      if (data[i].kahaoticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 3,
          money: data[i].kahaoticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 3,
          yeji: data[i].kahaoyeji,
          money: data[i].kahaoticheng,
          tichengbi: 0
        });
      }
      if (data[i].shougongticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 2,
          money: data[i].shougongticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 2,
          yeji: 0,
          money: data[i].shougongticheng,
          tichengbi: 0
        });
      }
      if (data[i].qitaticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 4,
          money: data[i].qitaticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 4,
          yeji: 0,
          money: data[i].qitaticheng,
          tichengbi: 0
        });
      }
      if (data[i].xianjinjieti > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 5,
          money: data[i].xianjinjieti,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 5,
          yeji: data[i].xianjinyeji,
          money: data[i].xianjinjieti,
          tichengbi: 0
        });
      }
      if (data[i].kahaojieti > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 6,
          money: data[i].kahaojieti,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 6,
          yeji: data[i].kahaoyeji,
          money: data[i].kahaojieti,
          tichengbi: 0
        });
      }
      data[i].id = '';
    }
    // console.log(data)
    const model = this.model('or_shop_userbasepay');
    await model.transaction(async() => {
      try {
        const res = fenpeitichengdata.length > 0 ? await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(fenpeitichengdata) : 1;

        const ot = ordertype == 1 ? 'KKD' : ordertype == 2 ? 'LSD' : 'CZD';

        const resdelticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: orderid, ordertype: ot}).delete();

        const resyejiticheng = data.length > 0 ? await this.model('or_shop_yejiticheng').db(model.db()).addMany(data) : 1;

        const baseInfo = basepay.length > 0 ? await model.addMany(basepay) : 1;

        const resorder = await this.model('or_shop_order').db(model.db()).where({id: orderid}).update({fenpei: 1, status: 2});

        if (resorder && res && baseInfo && resyejiticheng && resdelticheng !== false) {
          await model.commit();
          return this.success({info: '分配成功'});
        } else {
          await model.rollback();
          return this.fail('分配失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('分配失败');
      }
    });
  }

  async fanfenpeitichengAction() {
    const id = this.post('id');
    const shopid = this.shop_userinfo.departmentid;

    const orderinfo = await this.model('or_shop_order').where({id: id}).find();

    // 默认为流水单
    const isCanEditOrder = await this.isCanEditOrder(id, 'LSD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    const unix = new Date(orderinfo.addtime * 1000);
    const nYear = unix.getFullYear();
    let nMonth = unix.getMonth() + 1;
    nMonth = nMonth < 10 ? '0' + nMonth : nMonth;
    const jiesuandate = nYear + '' + nMonth;

    // 要做哪些内容，删除分配的业绩，删除分配的工资，订单表状态改变
    const model = this.model('or_shop_userbasepay');
    await model.transaction(async() => {
      try {
        const youticheng = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).select();
        // 判断当前是否有员工工资发放
        if (!think.isEmpty(youticheng)) {
          const allYejiTicList = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id}).select();
          let isfafang = 1;
          for (var i = allYejiTicList.length - 1; i >= 0; i--) {
            isfafang = await this.model('or_shop_usergongzi').db(model.db()).where({shopid: shopid, userid: allYejiTicList[i].userid, jiesuandate: jiesuandate}).select();
            if (!think.isEmpty(isfafang)) {
              await model.rollback();
              return this.fail('该订单时间段内有员工的工资已经发放！');
            }
            allYejiTicList[i].xianjinticheng = 0;
            allYejiTicList[i].kahaoticheng = 0;
            allYejiTicList[i].shougongticheng = 0;
            allYejiTicList[i].qitaticheng = 0;
            allYejiTicList[i].xianjinjieti = 0;
            allYejiTicList[i].kahaojieti = 0;
          }

          const resdelfen = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).delete();
          const delTicheng = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(allYejiTicList);
          const resdelub = await model.where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).delete();
          const allotfinis = await this.model('or_shop_order').db(model.db()).where({id: id}).update({fenpei: 0, status: 1});

          if (allotfinis && resdelfen !== false && resdelub !== false && delTicheng) {
            await model.commit();
            return this.success({info: '操作成功'});
          } else {
            await model.rollback();
            return this.fail('操作失败');
          }
        }
        const allotfinis = await this.model('or_shop_order').db(model.db()).where({id: id}).update({fenpei: 0, status: 1});
        await model.commit();
        return this.success({info: '操作成功'});
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('操作失败');
      }
    });
  }

  // 重新分配
  async chongxinfenpeiAction() {
    const data = JSON.parse(this.post('userinfo'));
    const orderid = this.post('orderid');
    const ordertype = this.post('ordertype');
    const addtime = Math.round(new Date().getTime() / 1000);
    let fenpeidata = [], paydata = [];

    let orderform = 'or_shop_order';

    if (ordertype == 10 || ordertype == 11) {
      orderform = 'or_shop_backcardorder';
    }

    const isCanEditOrder = await this.isCanEditOrder(orderid, ordertype);
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    const orderinfo = await this.model(orderform).where({id: orderid}).find();

    // 确定发放月份
    const unix = new Date(orderinfo.addtime * 1000);
    const nYear = unix.getFullYear();
    let nMonth = unix.getMonth() + 1;
    nMonth = nMonth < 10 ? '0' + nMonth : nMonth;
    const jiesuandate = nYear + '' + nMonth;

    let basepay = [], fenpeitichengdata = [];
    for (var i = data.length - 1; i >= 0; i--) {
      // 查询员工当月工资有没有发放
      const isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find();

      if (!think.isEmpty(isfafang)) {
        return this.fail('该订单时间段内有员工的工资已经发放！');
      }

      // 根据data去分配basetype
      if (data[i].xianjinticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 1,
          money: data[i].xianjinticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 1,
          yeji: data[i].xianjinyeji,
          money: data[i].xianjinticheng,
          tichengbi: 0
        });
      }
      if (data[i].kahaoticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 3,
          money: data[i].kahaoticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 3,
          yeji: data[i].kahaoyeji,
          money: data[i].kahaoticheng,
          tichengbi: data[i].kahaotichengbi ? data[i].kahaotichengbi : 0
        });
      }
      if (data[i].shougongticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 2,
          money: data[i].shougongticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 2,
          yeji: 0,
          money: data[i].shougongticheng,
          tichengbi: 0
        });
      }
      if (data[i].qitaticheng > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 4,
          money: data[i].qitaticheng,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 4,
          yeji: 0,
          money: data[i].qitaticheng,
          tichengbi: 0
        });
      }
      if (data[i].xianjinjieti > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 5,
          money: data[i].xianjinjieti,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 5,
          yeji: data[i].xianjinyeji,
          money: data[i].xianjinjieti,
          tichengbi: 0
        });
      }
      if (data[i].kahaojieti > 0) {
        basepay.push({
          userid: data[i].userid,
          category: 2,
          type: 6,
          money: data[i].kahaojieti,
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          time: orderinfo.addtime
        });
        fenpeitichengdata.push({
          orderid: data[i].orderid,
          ordertype: ordertype,
          addtime: addtime,
          userid: data[i].userid,
          type: 6,
          yeji: data[i].kahaoyeji,
          money: data[i].kahaojieti,
          tichengbi: 0
        });
      }
      data[i].id = '';
    }

    const model = this.model('or_shop_userbasepay');
    await model.transaction(async() => {
      try {
        // 先删除以前的
        const sulist = await this.model('or_shop_userbasepay')
          .db(model.db())
          .where({orderid: orderid, ordertype: ordertype})
          .select();

        for (var i = sulist.length - 1; i >= 0; i--) {
          const isfafang = await this.model('or_shop_usergongzi').db(model.db()).where({userid: sulist[i].userid, jiesuandate: jiesuandate}).find();
          if (!think.isEmpty(isfafang)) {
            await model.rollback();
            return this.fail('有员工工资已经审核不能再分配');
          }
        }

        const delfp = await this.model('or_shop_fenpeiticheng')
          .db(model.db())
          .where({orderid: orderid, ordertype: ordertype})
          .delete();

        const delub = await this.model('or_shop_userbasepay')
          .db(model.db())
          .where({orderid: orderid, ordertype: ordertype})
          .delete();

        const ot = ordertype == 1 ? 'KKD' : ordertype == 2 ? 'LSD' : 'CZD';

        const delyejiticheng = await this.model('or_shop_yejiticheng').where({orderid: orderid, ordertype: ot}).db(model.db()).delete();

        const resfp = fenpeitichengdata.length > 0 ? await this.model('or_shop_fenpeiticheng')
          .db(model.db())
          .addMany(fenpeitichengdata)
          :				1;
        const resub = basepay.length > 0 ? await model.addMany(basepay) : 1;

        const resticheng = data.length > 0 ? await this.model('or_shop_yejiticheng').db(model.db()).addMany(data) : 1;

        if (resticheng && resub && resfp && delub !== false && delfp !== false && delyejiticheng !== false) {
          await model.commit();
          return this.success({info: '分配成功'});
        } else {
          await model.rollback();
          return this.fail('分配失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('分配失败');
      }
    });
  }

  async tuidanlistAction() {
    const searchinfo = JSON.parse(this.post('searchinfo'));

    const where = {
      'o.departmentid': this.shop_userinfo.departmentid
    };

    if (searchinfo.times && (searchinfo.times[0] != null && searchinfo.times[1] != null)) {
      const begintime = Math.floor(new Date(searchinfo.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(searchinfo.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400; // 当天加上一天
      where['o.addtime'] = {'>=': begintime, '<': endtime};
    }

    if (searchinfo.ordertype != 0) where['o.ordertype'] = searchinfo.ordertype;
    where['o.status'] = searchinfo.status == 0 ? ['!=', 0] : searchinfo.status;
    if (searchinfo.search) where['g.name'] = ['like', '%' + searchinfo.search + '%'];

    const list = await this.model('or_shop_backcardorder')
      .alias('o')
      .field('o.*, g.name, g.id as gid')
      .join('`think_or_guest` g on g.id=o.guestid')
      .where(where)
      .page(searchinfo.currentPage, searchinfo.pageSize)
      .order('o.addtime desc')
      .countSelect();

    return this.json(list);
  }
}
